use async_trait::async_trait;
use mf_state::{Transaction, transaction::Command};
use mf_transform::TransformResult;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct DeleteCommand {
    pub point_id: Box<str>,
}

impl DeleteCommand {
    pub fn new(point_id: Box<str>) -> Self {
        Self { point_id }
    }
}

#[async_trait]
impl Command for DeleteCommand {
    async fn execute(
        &self,
        tr: &mut Transaction,
    ) -> TransformResult<()> {
        let doc = tr.doc();
        let point_node = doc.get_node(&self.point_id);
        if point_node.is_none() {
            return Err(anyhow::anyhow!("目标节点不存在，删除失败".to_string()));
        }
        let point_node = doc.get_parent_node(&self.point_id);
        if let Some(node) = point_node {
            tr.remove_node(node.id.clone(), vec![self.point_id.clone()])?;
        }
        Ok(())
    }

    fn name(&self) -> String {
        "DeleteCommand".to_string()
    }
}
